import { history, IRouteComponentProps, useLocation } from 'umi';
import Header from './Header';
import layoutStyle from './index.less';
import React, { useMemo, useState } from 'react';
import {
  IconBookmark,
  IconList,
  IconPriceTag,
  IconUser,
} from '@douyinfe/semi-icons';
import { Nav } from '@douyinfe/semi-ui';

export default function Layout({
  children,
  location,
  route,
  history,
  match,
}: IRouteComponentProps) {
  if (location.pathname.indexOf('/admin') !== -1) {
    return (
      <>
        <Header />
        <div className={layoutStyle.admin_conents_container}>
          <NavApp />
          <div style={{ flex: '2' }}>{children}</div>
        </div>
      </>
    );
  }

  return (
    <>
      <Header />
      <div
        className={[layoutStyle.content_container, 'content_container'].join(
          ' ',
        )}
      >
        {children}
      </div>
    </>
  );
}

function NavApp(props = {}) {
  const location = useLocation();
  const [openKeys, setOpenKeys] = useState(['/admin/bookmarkConfig']);
  let [selectedKeys, setSelectedKeys] = useState([location.pathname]);
  const [isCollapsed, setIsCollapsed] = useState(false);
  selectedKeys = [location.pathname];

  const onSelect = (data: any) => {
    history.push(data.itemKey);
    console.log('data', data);
    setSelectedKeys([...data.selectedKeys]);
  };

  const onOpenChange = (data: any) => {
    console.log('trigger onOpenChange: ', data);
    setOpenKeys([...data.openKeys]);
  };

  const onCollapseChange = (isCollapsed: any) => {
    console.log('isCollapsed', isCollapsed);
    setIsCollapsed(isCollapsed);
  };

  const items = useMemo(
    () => [
      { itemKey: '/admin', text: '控制台', icon: <IconUser /> },
      {
        itemKey: '/admin/bookmarkConfig',
        text: '书签管理',
        icon: <IconBookmark />,
        items: [
          {
            icon: <IconPriceTag />,
            itemKey: '/admin/classify',
            text: '书签分类',
          },
          {
            icon: <IconList />,
            itemKey: '/admin/bookmark',
            text: '书签列表',
          },
        ],
      },
    ],
    [],
  );

  return (
    <Nav
      isCollapsed={isCollapsed}
      openKeys={openKeys}
      selectedKeys={selectedKeys}
      bodyStyle={{ height: '85vh' }}
      items={items}
      footer={{
        collapseButton: true,
      }}
      onCollapseChange={onCollapseChange}
      onOpenChange={onOpenChange}
      onSelect={onSelect}
    />
  );
}
